package com.epfresh.fragment;


import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.epfresh.R;
import com.epfresh.activity.CartActivity;
import com.epfresh.activity.CenterListActivity;
import com.epfresh.activity.CommentNewActivity;
import com.epfresh.activity.CommonStoreActivity;
import com.epfresh.activity.DcStoreActivity;
import com.epfresh.activity.DetailGoodsActivity;
import com.epfresh.activity.HomeActivity;
import com.epfresh.activity.LoginActivity;
import com.epfresh.activity.OrderLogisticsInfoActivity;
import com.epfresh.activity.OrderMinusRecordActivity;
import com.epfresh.activity.SearchActivity;
import com.epfresh.api.entity.RequestEntityMap;
import com.epfresh.api.entity.RequestTag;
import com.epfresh.api.entity.ResponseEntity;
import com.epfresh.api.helper.ApplicationHelper;
import com.epfresh.api.http.OnRequestListener;
import com.epfresh.api.utils.AppUtils;
import com.epfresh.bean.StoreDetail;
import com.epfresh.constant.Constant;
import com.epfresh.global.BaseFragment;
import com.epfresh.global.DataManager;
import com.epfresh.jsbridge.BridgeHandler;
import com.epfresh.jsbridge.BridgeWebView;
import com.epfresh.jsbridge.BridgeWebViewClient;
import com.epfresh.jsbridge.CallBackFunction;
import com.epfresh.views.stick.OnStickyListener;
import com.epfresh.views.stick.ScrollWebView;
import com.epfresh.wxapi.WXPayEntryActivity;
import com.google.gson.Gson;

import static android.app.Activity.RESULT_OK;
import com.epfresh.api.utils.FileUtil;


public class H5AllGoodsFragment extends BaseFragment {
    private BridgeWebView webview;
    private ProgressBar pb;
    private String title;
    private int pushType = 2;

    private String orderId;
    //是否需要刷新订单
    private boolean isRefresh;


    public void updateData() {
        //this.url = url;
        if (!TextUtils.isEmpty(urlOnly) && webview != null) {
            String url = getOrderUrl();
            if (!TextUtils.isEmpty(url)) {
                webview.loadUrl(url);
            }
        }

    }

    public boolean clickBack(int keycode,KeyEvent event){
        if(keycode== KeyEvent.KEYCODE_BACK&&webview!=null&&webview.canGoBack()){
            webview.goBack();
        }
        return true;
    }

    public boolean clickBack(){
        if(webview!=null&&webview.canGoBack()){
            webview.goBack();
            return true;
        }
        return false;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.activity_js_web, container, false);
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        pb = view.findViewById(R.id.pb);
        webview = view.findViewById(R.id.wv);
        pb.setVisibility(View.VISIBLE);
        webViewSetting();
        String url = getOrderUrl();
        if (!TextUtils.isEmpty(url)) {
            webview.loadUrl(url);
        }
    }
    String urlOnly = "http://mtest.epfresh.com/classificationGoods/index.html?";
    public String getOrderUrl() {
        String token = getUser().getAccess_token();
        String accountId = getUser().getAccountId();
        String cityId = ApplicationHelper.getInstance().getCity().getCityId();
        String url = urlOnly + "token=" + token + "&accountId=" + accountId + "&cityId=" + cityId;
        url += "&cid=" + AppUtils.getUniquePsuedoID();
        SharedPreferences sp = FileUtil.getSharedPreferences();
        if(sp.getInt("h5Goods",0)==0){
            SharedPreferences.Editor edit = sp.edit();
            edit.putInt("h5Goods", 1);
            edit.commit();
            url += "&first="+true;
        }
        //url = "http://10.250.112.183:8088/classificationGoods/index.html?token=2124b85a6ec04bfcba23de3e9ecff9cb&cityId=6401&cid=ffffffff-e8f2-39be-ffff-ffffde6d6dc2&accountId=37";
        Log.e("url", "" + url);
        return url;
    }

    public void webViewSetting() {
        WebSettings settings = webview.getSettings();

        settings.setJavaScriptEnabled(true);//启用js
        settings.setJavaScriptCanOpenWindowsAutomatically(true);//js和android交互
        settings.setAllowFileAccess(true); // 允许访问文件
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setAppCacheEnabled(false); //设置H5的缓存打开,默认关闭
        settings.setUseWideViewPort(true);//设置webview自适应屏幕大小
        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);//设置，可能的话使所有列的宽度不超过屏幕宽度
        settings.setLoadWithOverviewMode(true);//设置webview自适应屏幕大小
        settings.setDomStorageEnabled(true);//设置可以使用localStorage
        settings.setSupportZoom(false);//关闭zoom按钮
        settings.setBuiltInZoomControls(false);//关闭zoom
        webview.setLayerType(View.LAYER_TYPE_SOFTWARE, null);


        webview.setDefaultHandler(new BridgeHandler() {
            @Override
            public void handler(String data, CallBackFunction function) {
                //Toast.toast("" + data);
                Log.e("DefaultHandler", "functionInJs, data from web = " + data);
                function.onCallBack("返回");
            }
        });
        webview.registerHandler("submitFromWeb", new BridgeHandler() {

            @Override
            public void handler(String data, CallBackFunction function) {
                //toast("" + data);
                Log.i("submitFromWeb", "handler = submitFromWeb, data from web = " + data);
                function.onCallBack("submitFromWeb exe, response data 中文 from Java");
            }

        });
        webview.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress > 99) {
                    pb.setVisibility(View.GONE);
                } else {
                    if (pb.getVisibility() == View.GONE)
                        pb.setVisibility(View.VISIBLE);
                    pb.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                if (title != null && !"".equals(title)) {
                 //   toolbarTitle.setText(title);
                }
            }



        });
        webview.setWebViewClient(new BridgeWebViewClient(webview) {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Log.e("url", "url:" + url);
                if (url != null && url.startsWith("epfreshbuyerclick://home_category_goods") && getContext() != null) {
                    Intent intent = new Intent(getContext(), DetailGoodsActivity.class);
                    String id = Uri.parse(url).getQueryParameter("productId");
                    String promotionId = Uri.parse(url).getQueryParameter("promotionId");
                    intent.putExtra("storeId",Uri.parse(url).getQueryParameter("storeId"));
                    intent.putExtra("id", id);
                    intent.putExtra("promotionItemId",promotionId);
                    startActivity(intent);
                    return true;
                }else if (url != null && url.startsWith("epfreshbuyerclick://home_category_cart_fresh") && getContext() != null) {
                    DataManager.getInstance().oftenListReFresh = true;
                    return true;
                }else if (url != null && url.startsWith("epfreshbuyerclick://home_category_offer_fresh") && getContext() != null) {
                    DataManager.getInstance().oftenListReFresh = true;
                    return true;
                }else if (url != null && url.startsWith("epfreshbuyerclick://promotionproduct") && getContext() != null) {
                    Intent intent = new Intent(getContext(), DetailGoodsActivity.class);
                    String id = Uri.parse(url).getQueryParameter("productId");
                    String promotionId = Uri.parse(url).getQueryParameter("promotionId");
                    intent.putExtra("storeId",Uri.parse(url).getQueryParameter("storeId"));
                    intent.putExtra("id", id);
                    intent.putExtra("promotionItemId",promotionId);
                    startActivity(intent);
                    return true;
                }else if (url != null && url.startsWith("epfreshbuyerclick://home_category_store") && getContext() != null) {
//                    SalesType=1整货,SalesType=2散货
                    String salesType = Uri.parse(url).getQueryParameter("salestype");
                    if ("2".equals(salesType)) {
                        requestDc(false,Uri.parse(url).getQueryParameter("storeId"));
                    } else {
                        String id = Uri.parse(url).getQueryParameter("storeId");
                        Intent intent = new Intent(getContext(), CommonStoreActivity.class);
                        intent.putExtra("storeId", id);
                        startActivity(intent);
                    }
                    return true;
                } else if (url != null && url.startsWith("epfreshbuyerclick://home_category_cart") && getContext() != null) {
                    Intent intent = new Intent(getContext(), CartActivity.class);
                    startActivity(intent);
                    //((HomeActivity)getAppActivity()).onTabSelect(2);
                    return true;
                } else if (url != null && url.startsWith("epfreshbuyerclick://home_category_search") && getContext() != null) {
                    Intent search = new Intent(getActivity(), SearchActivity.class);
                    startActivity(search);
                    return true;
                } else if (url != null && url.startsWith("epfreshbuyerclick://order") && getContext() != null) {
                    Intent intent = new Intent(getContext(), OrderLogisticsInfoActivity.class);
                    String id = Uri.parse(url).getQueryParameter("id");
                    intent.putExtra("logisticsNo", id);
                    startActivity(intent);
                    Log.e(")_____________________", id);
                    return true;
                } else if (url != null && url.startsWith("tel:")) {//电话
                    Intent intent = new Intent(Intent.ACTION_VIEW,
                            Uri.parse(url));
                    startActivity(intent);
                    return true;
                } else if (url != null && url.startsWith("epfreshbuyerclick://pay")) {//直接支付
                    Intent pay = new Intent(getContext(), WXPayEntryActivity.class);
                    pay.putExtra("payWay", 1);
                    String orderId = Uri.parse(url).getQueryParameter("id");
                    pay.putExtra("orderId", orderId);
                    startActivity(pay);
                    return true;
                } else if (url != null && url.startsWith("epfreshbuyerclick://surepay")) {//确认收货,有尾款
                    Intent pay = new Intent(getContext(), WXPayEntryActivity.class);
                    String orderId = Uri.parse(url).getQueryParameter("id");
                    pay.putExtra("orderId", orderId);
                    pay.putExtra("type", "2");
                    startActivity(pay);
                    return true;
                } else if (url != null && url.startsWith("epfreshbuyerclick://again")) {
                    Intent intent = new Intent(getContext(),
                            HomeActivity.class);
                    intent.putExtra("home_tab_index", 2);
                    DataManager.getInstance().isNeedRefreshCart = true;
                    startActivity(intent);

                    return true;
                } else if (url != null && url.startsWith("epfreshbuyerclick://notify")) {//通知更新
                    isRefresh = true;
                    return true;
                } else if (url != null && url.startsWith("epfreshbuyerclick://loginexc")) {//登陆异常
                    Intent intent = new Intent(getContext(), LoginActivity.class);
                    intent.putExtra("relogin", true);
                    startActivityForResult(intent, 0x001);
                    return true;
                } else {
//                    view.loadUrl(url);
                    return super.shouldOverrideUrlLoading(view, url);
                }
//                return false;
            }
        });

        webview.callHandler("functionInJs", "dffsdafsdf", new CallBackFunction() {
            @Override
            public void onCallBack(String data) {
                Log.e("functionInJs", "functionInJs, data from web = " + data);
            }
        });
    }
    @Override
    public String getBaseTag() {
        return null;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 0x001 && resultCode == RESULT_OK) {
            webview.clearHistory();
            String url = getOrderUrl();
            webview.loadUrl(url);
            isRefresh = true;
        }
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        if (outState == null) {
            outState = new Bundle();
        }
        outState.putString(Constant.KEY_WEB_URL, urlOnly);
        outState.putString(Constant.KEY_WEB_TITLE, title);
        super.onSaveInstanceState(outState);
    }
    @Override
    public void onClick(View view) {
        //super.onClick(view);
        switch (view.getId()) {
            case R.id.baseback:
                // 返回上一页
                //onBackPressed();
                break;
        }
    }
/*

    @Override
    public void onBackPressed() {
        if (webview.canGoBack()) {
            webview.goBack();
            basetitle.setText("订单详情");
        } else if (pushType == 0) {
            Intent main = new Intent(getApplicationContext(), HomeActivity.class);
            startActivity(main);
            finish();
        } else if (pushType == 1) {
            finish();
        } else {
            finish();
        }
    }
*/



    @Override
    public void onDestroy() {
        if (webview != null) {
            webview.destroy();
        }
        super.onDestroy();
    }
    public void requestDc(boolean isSilent,String id) {

        RequestEntityMap re = new RequestEntityMap();
        re.setCmd(com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_store_dcStore);
        re.putParameter("storeId",id);
        RequestTag requestTag = new RequestTag();
        requestTag.tag = com.epfresh.api.constant.AppPurchaseRouterConstant.cmd_store_store_dcStore;
        if (isSilent) {
            requestTag.type = RequestTag.TYPE_CURRENT;
            requestTag.arg1 = "silent";
            re.setCityId(ApplicationHelper.getInstance().getCity().getCityId());
            ApplicationHelper.getInstance().requestSilent(re, requestTag, onDetailRequestListener);
//                request(re, requestTag, onDetailRequestListener);
        } else {
            requestTag.arg1 = "1";
            request(re, requestTag, onDetailRequestListener);
        }

    }


    OnRequestListener<StoreDetail> onDetailRequestListener = new OnRequestListener<StoreDetail>() {
        @Override
        public StoreDetail jsonToObj(String s) {
            return new Gson().fromJson(s, StoreDetail.class);
        }

        @Override
        public void onFail(int i, Object o, Object o1) {

            if (o1 != null && o1 instanceof RequestTag) {
                RequestTag tag = (RequestTag) o1;
                if ("silent".equals(tag.arg1)) {

                } else {
                    hideProgressDialog();
                }
            } else {
                hideProgressDialog();
            }

        }

        @Override
        public void onResponseError(int i, Object o, Object o1) {

            if (o1 != null && o1 instanceof RequestTag) {
                RequestTag tag = (RequestTag) o1;
                if ("silent".equals(tag.arg1)) {

                } else {
                    hideProgressDialog();
                }
            } else {
                hideProgressDialog();
            }

        }

        @Override
        public void onStart(Object o1) {
            if (o1 != null && o1 instanceof RequestTag) {
                RequestTag tag = (RequestTag) o1;
                if ("silent".equals(tag.arg1)) {

                } else {
                    showProgressDialog();
                }
            } else {
                showProgressDialog();
            }

        }

        @Override
        public void onResponse(ResponseEntity<StoreDetail> responseEntity, Object o1) {

            StoreDetail responseElement = responseEntity.getResponseElement();
            if (responseElement != null) {

            }
            if (o1 != null && o1 instanceof RequestTag) {
                RequestTag tag = (RequestTag) o1;
                if ("silent".equals(tag.arg1)) {

                } else {
                    hideProgressDialog();
                    intoDcPage(responseElement);
                }
            } else {
                hideProgressDialog();
                intoDcPage(responseElement);
            }


        }
    };

    public void intoDcPage(StoreDetail responseElement) {
        if (responseElement != null) {
            if (!responseElement.isResult()) {
                Intent tv_more = new Intent(getContext(),
                        CenterListActivity.class);
                startActivity(tv_more);
            } else {
                Intent tv_bulk_load = new Intent(getContext(),
                        DcStoreActivity.class);
                tv_bulk_load.putExtra("data", new Gson().toJson(responseElement));
                startActivity(tv_bulk_load);
            }
        }
    }
}
